//
//  SSWBUserAccount.swift
//  shanshanlol微博
//
//  Created by 叶竞泽 on 2017/1/19.
//  Copyright © 2017年 JingZe. All rights reserved.
//

import UIKit

private let accountFile = ("userAccount.json" as NSString).cz_appendDocumentDir()

/// 用户账户信息
class SSWBUserAccount: NSObject {

    /// 访问令牌
    var access_token: String? {
        didSet {
            if access_token == nil {
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil, userInfo: nil)
            }
        }
    }
    
    /// 过期日期 - 单位:秒, 开发者是5年,使用者是3天
    var expires_in: TimeInterval = 0 {
        
        didSet {
            expires_date = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 过期日期
    var expires_date: Date?
    
    /// uid
    var uid: String?
    
    /// 用户昵称
    var screen_name: String?
    
    /// 用户头像大图 180 * 180
    var avatar_large: String?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        
        // 1.从磁盘加载保存的文件 -> 字典
        guard let path = accountFile, let data = NSData.init(contentsOfFile: path), let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject] else {
            return
        }
        
        // 2.使用字典设置对象属性
        // 用户是否登录的关键
        yy_modelSet(with: dict ?? [:])
        
        // 3.比较过期时间,测试是否过期
        if expires_date?.compare(Date()) != .orderedDescending {
            print("账户过期")
            // 清空token
            access_token = nil
            uid = nil
            // 删除账户文件
            try? FileManager.default.removeItem(atPath: path)
        }
        
        print("账户正常\(self)")
    }
    
    /*
     1.偏好设置(小) - Xcode 8 beta 无效
     2.沙盒-归档/plist/json(本例使用json)
     3.数据库(FMDB/coreData)
     4.钥匙串访问(小,自动加密 - 需要使用框架 SSKeychain)
    */
    func saveAccount() {
        
        // 1.模型转字典
        var dict = yy_modelToJSONObject() as? [String: AnyObject] ?? [:]
        
        // 2.字典序列化为Data
        // 首先删除expires_in
        let _ = dict.removeValue(forKey: "expires_in")
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted), let filePath = accountFile else {
            return
        }
        
        // 3.写入磁盘
        let _ = (data as NSData).write(toFile: filePath, atomically: true)
        
        print("用户账户保存成功\(filePath)")
        
    }
}
